package com.self.cloudmall.common.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import com.self.cloudmall.common.enumm.ResultErrorEum;
import com.self.cloudmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Configuration
public class SentinelWebConfig {

    /**
     * 全局配置限流后返回的数据
      * @return
     */
  @Bean
  public BlockExceptionHandler blockExceptionHandler(){
      log.info("统一限流后返回结果格式。。。。。。");
      return (HttpServletRequest request, HttpServletResponse response, BlockException e)->{
          log.error("请求uri:{},发生限流：{}",request.getRequestURI(),e);
          response.setCharacterEncoding("UTF-8");
          response.setContentType("application/json");
          R error = R.error(ResultErrorEum.SENTINEL_BLOCK_ERROR.getCode(), ResultErrorEum.SENTINEL_BLOCK_ERROR.getMessage());
          PrintWriter writer = response.getWriter();
          writer.print(JSONObject.toJSONString(error));
          writer.flush();
          writer.close();
      };
  }
}
